package com.zty.utils.impl;

import com.zty.BO.ServerInfo;
import com.zty.errors.BusinessException;
import com.zty.errors.EnumMetaException;
import com.zty.utils.ServerSelector;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author ZTY
 * @Description
 * @Date 0:49 2023-12-24
 **/

public class DefaultServerSelector implements ServerSelector {
    @Override
    public List<ServerInfo> select(List<ServerInfo> aliveServers, int count) {
        if (aliveServers.size()<count){
            throw new BusinessException("存活的服务数量小于分片存储数量", EnumMetaException.NOT_ENOUGH_CHUNK_SERVER);
        }

        //  使用随机策略（洗牌法）
        int[] idxArray = new int[aliveServers.size()];
        for (int i = 0; i < idxArray.length; i++) {
            idxArray[i] = i;
        }
        //  洗牌法并发场景下可能出现问题
        for (int i = 0; i < count; i++) {
            int randomIndex = (int) (Math.random() * aliveServers.size());
            int tmp = idxArray[randomIndex];
            idxArray[randomIndex] = idxArray[i];
            idxArray[i] = tmp;
        }

        //此时已经将下标全部打乱了
        List<ServerInfo> selectedServers = new ArrayList<>();
        for (int i = 0; i < count; i++) {
            selectedServers.add(aliveServers.get(idxArray[i]));
        }
        return selectedServers;
    }
}
